package com.beilang.hotline.telrecord.page;

import com.beilang.base.codelookup.manager.CodeLookupMgr;
import com.beilang.base.codelookup.model.CodeModel;
import com.beilang.base.core.model.LabelValueBean;
import com.beilang.base.core.page.BasePage;
import com.beilang.base.pagination.PaginationHelper;
import com.beilang.base.util.*;
import com.beilang.hotline.email.manager.EmailServerMgr;
import com.beilang.hotline.email.model.EmailServerModel;
import com.beilang.hotline.login.UserAccessTO;
import com.beilang.hotline.person.model.PersonModel;
import com.beilang.hotline.telattach.manager.TelattachMgr;
import com.beilang.hotline.telattach.model.TelattachModel;
import com.beilang.hotline.telrecord.manager.TelrecordMgr;
import com.beilang.hotline.telrecord.model.TelrecordModel;
import com.beilang.hotline.telreply.manager.TelreplyMgr;
import com.beilang.hotline.telreply.model.TelreplyModel;
import com.beilang.hotline.user.manager.UserMgr;
import com.beilang.hotline.user.model.UserModel;
import flex.messaging.FlexContext;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

public class TelRecordPage extends BasePage {
    private CodeLookupMgr codeLookupMgr;
    private TelrecordMgr telrecordMgr;
    private TelattachMgr telattachMgr;
    private TelreplyMgr telreplyMgr;
    private EmailServerMgr emailServerMgr;
    private UserMgr userMgr;

    public void setUserMgr(UserMgr userMgr) {
        this.userMgr = userMgr;
    }

    public void setEmailServerMgr(EmailServerMgr emailServerMgr) {
        this.emailServerMgr = emailServerMgr;
    }

    public void setCodeLookupMgr(CodeLookupMgr codeLookupMgr) {
        this.codeLookupMgr = codeLookupMgr;
    }

    public void setTelrecordMgr(TelrecordMgr telrecordMgr) {
        this.telrecordMgr = telrecordMgr;
    }


    public void setTelattachMgr(TelattachMgr telattachMgr) {
        this.telattachMgr = telattachMgr;
    }

    public TelrecordModel saveTelrecordModel(TelrecordModel telrecordModel, String isLastChange, String emailuser) {
        if (!StringUtil.isEmpty(telrecordModel.getRecordTimeStr())) {
            Date dt = DateUtil.parseDateTimeHHMM(telrecordModel.getRecordTimeStr());
            telrecordModel.setRecordTime(dt);
        }

        ArrayList tolist = new ArrayList();
        TelreplyModel telreplyModel = new TelreplyModel();
        EmailServerModel emailServerModel = emailServerMgr.getEmailServer();
        String from = emailServerModel.getEmailFrom();
        String displayName = emailServerModel.getEmailDisplayName();
        String mailhost = emailServerModel.getSmtpServer();
        String userName = emailServerModel.getEmailUserName();
        String password = emailServerModel.getEmailPassword();
        String mailSubject = emailServerModel.getEmailSubject();
        //String mailModifySubject = "事务修改通知";

        TelrecordModel telrecordModelxx = getTelRecord(telrecordModel.getRecordId());
        UserModel loginUser = this.getLoginUser();

        //if status is close，reopen
        if (Constant.STATUS_COMPLETE.equals(telrecordModelxx.getRecordStatus())) {
            telrecordModel.setRecordStatus(Constant.STATUS_INPROGRESS);
        }

        if ((!telrecordModelxx.getCurrentOwner().equals(telrecordModel.getCurrentOwner())
                && !StringUtil.isEmpty(telrecordModel.getCurrentOwner()))) {
            //add reply record

            UserModel user = this.getLoginUser();
            telreplyModel.setReplyFrom(user.getUserId());
            telreplyModel.setReplyBy(telrecordModel.getCurrentOwner());
            if (user != null) {
                telreplyModel.setCreateId(user.getUserId());
                telreplyModel.setUpdateId(user.getUserId());
            }
            Date date = DateUtil.getDate();
            telreplyModel.setRecordId(telrecordModelxx.getRecordId());
            telreplyModel.setCreateTime(date);
            telreplyModel.setUpdateTime(date);
            telreplyModel.setReplyTime(date);
            telreplyModel.setKeyrecordInd(Constant.NO);
            telreplyModel = telreplyMgr.createTelreplyModel(telreplyModel);

            UserModel userModel1 = userMgr.getUser(telrecordModel.getCurrentOwner());
            UserModel userModel2 = userMgr.getUser(telrecordModel.getCreateId());
            UserModel userModel3 = userMgr.getUser(telrecordModelxx.getCurrentOwner());

            if (!StringUtil.isEmpty(emailuser)) {
                String[] s = emailuser.split("\\|");
                for (int i = 0; i < s.length; i++) {
                    UserModel us = userMgr.getUser(s[i]);
                    if (!tolist.contains(us.getEmailAddress())) {
                        tolist.add(us.getEmailAddress());
                    }
                }
            }

            if (!StringUtil.isEmpty(userModel1.getEmailAddress())
                    && !loginUser.getUserId().equalsIgnoreCase(userModel1.getUserId())
                    && !tolist.contains(userModel1.getEmailAddress())) {
                tolist.add(userModel1.getEmailAddress());
            }
            if (!StringUtil.isEmpty(userModel2.getEmailAddress())
                    && !loginUser.getUserId().equalsIgnoreCase(userModel2.getUserId())
                    && !tolist.contains(userModel2.getEmailAddress())) {
                tolist.add(userModel2.getEmailAddress());
            }
            if (!StringUtil.isEmpty(userModel3.getEmailAddress())
                    && !loginUser.getUserId().equalsIgnoreCase(userModel3.getUserId())
                    && !tolist.contains(userModel3.getEmailAddress())) {
                tolist.add(userModel3.getEmailAddress());
            }


        } else {
            if (Constant.YES.equals(isLastChange)) {
                UserModel userModel1 = userMgr.getUser(telrecordModel.getCurrentOwner());
                UserModel userModel2 = userMgr.getUser(telrecordModel.getCreateId());

                if (!StringUtil.isEmpty(emailuser)) {
                    String[] s = emailuser.split("\\|");
                    for (int i = 0; i < s.length; i++) {
                        UserModel us = userMgr.getUser(s[i]);
                        if (!tolist.contains(us.getEmailAddress())) {
                            tolist.add(us.getEmailAddress());
                        }
                    }
                }
                if (!StringUtil.isEmpty(userModel1.getEmailAddress())
                        && !loginUser.getUserId().equalsIgnoreCase(userModel1.getUserId())
                        && !tolist.contains(userModel1.getEmailAddress())) {
                    tolist.add(userModel1.getEmailAddress());
                }
                if (!StringUtil.isEmpty(userModel2.getEmailAddress())
                        && !loginUser.getUserId().equalsIgnoreCase(userModel2.getUserId())
                        && !tolist.contains(userModel2.getEmailAddress())) {
                    tolist.add(userModel2.getEmailAddress());
                }
            }
        }

        if (!tolist.isEmpty()) {
            telrecordModel = telrecordMgr.setTelrecordModelDesc(telrecordModel);
            telreplyModel = telreplyMgr.setTelreplyModelDesc(telreplyModel);
            SendEmailUtil.sendMail(from, displayName, tolist, mailhost, userName, password, mailSubject, telreplyModel, telrecordModel, emailServerModel);
        }
        telrecordModel = telrecordMgr.saveTelrecord(telrecordModel);

        return telrecordModel;
    }

    public TelrecordModel getTelRecord(Long recordId) {
        return telrecordMgr.getTelrecord(recordId);
    }

    public String getLogUser() {
        UserModel userModel = this.getLoginUser();
        return userModel.getUserId();
    }

    public void deleteTelrecord(Long recordId) {
        List list = new ArrayList();
        list = telattachMgr.searchRecordAttachList(recordId, "rd");
        deleteAttachTOList(list);
        List list1 = telreplyMgr.searchTelreplyList(recordId, false);
        if (list1 != null && !list1.isEmpty()) {
            Iterator itor1 = list1.iterator();
            while (itor1.hasNext()) {
                TelreplyModel telreplyModel = (TelreplyModel) itor1.next();
                List list2 = telattachMgr.searchRecordAttachList(telreplyModel.getReplyId(), "ry");
                deleteAttachTOList(list2);
                telreplyMgr.deleteTelreply(telreplyModel.getReplyId());
            }
        }
        telrecordMgr.deleteTelrecord(recordId);
    }

    public void deleteAttachTOList(List list) {
        if (list != null && !list.isEmpty()) {
            Iterator itor = list.iterator();
            while (itor.hasNext()) {
                TelattachModel telattachModel = (TelattachModel) itor.next();
                telattachMgr.deleteTelattach(telattachModel.getAttachId());
            }
        }
    }

    public void setTelreplyMgr(TelreplyMgr telreplyMgr) {
        this.telreplyMgr = telreplyMgr;
    }

    public String initialSession(Long recordId) {
        TelrecordModel telrecordModel = telrecordMgr.getTelrecord(recordId);
        if (telrecordModel != null) {
            if (getLoginUser() == null) {
                String accesInd = telrecordModel.getAccessInd();
                if (Constant.NO.equals(accesInd)) {
                    telrecordModel.setAccessInd(Constant.YES);
                    telrecordMgr.saveTelrecord(telrecordModel);
                    String userId = telrecordModel.getCreateId();
                    UserModel userModel = userMgr.getUser(userId);

                    //List accessList = userModel.getAccessSystemList();
                    UserAccessTO accessTO = new UserAccessTO(userModel.getUserRole());

                    accessTO.setUserInd(false);
                    accessTO.setModuleInd(false);
                    accessTO.setEmailInd(false);
                    accessTO.setIssueInd(false);
                    accessTO.setCompanyInd(false);
                    accessTO.setPersonInd(false);
                    accessTO.setExportInd(false);
                    accessTO.setHistoryExportInd(false);
                    accessTO.setHistoryDownloadInd(false);
                    accessTO.setHistoryAddInd(false);
                    accessTO.setHistoryCloseInd(false);
                    accessTO.setHistoryDeleteInd(false);
                    accessTO.setHistoryModifyInd(false);
                    accessTO.setHistoryProcessInd(false);
                    accessTO.setPopInd(true);
                    userModel.setUserAccessTO(accessTO);
                    FlexContext.getFlexSession().setAttribute("user", userModel);
                    return Constant.YES;
                } else {
                    return Constant.NO;
                }
            } else {
                return Constant.YES;
            }
        } else {
            return Constant.NO;
        }
    }

    public UserModel getSession() {
        return this.getLoginUser();
    }

    public List getSearchPersonList(Long companyId) {
        List param = new ArrayList();
        param.add(companyId);
        List list = codeLookupMgr.getCodeListWithFilter(CodeConstant.PERSON_LIST, CodeConstant.CODE_FILTER, param, true);
        return list;
    }

    public List getSearchIssueList(Long systemId) {
        List param = new ArrayList();
        param.add(systemId);
        List list = new ArrayList();
        list.add(getEmptyIntCodeModel());
        List list1 = codeLookupMgr.getCodeListWithFilter(CodeConstant.ISSUE_LIST, CodeConstant.CODE_FILTER, param);
        list.addAll(list1);
        return list;
    }

    public List getSearchModuleList(Long systemId) {
        List param = new ArrayList();
        param.add(systemId);
        List list = new ArrayList();
        list.add(getEmptyIntCodeModel());
        List list1 = codeLookupMgr.getCodeListWithFilter(CodeConstant.MODULE_LIST, CodeConstant.CODE_FILTER, param);
        list.addAll(list1);
        return list;
    }

    public List getEmailSearchUserList() {
        //search 创建人

        List list = codeLookupMgr.getCodeListWithFilter(CodeConstant.USER_LIST, CodeConstant.CODE_FILTER, new ArrayList());
        if (list != null && list.size() > 0) {
            List l = new ArrayList();
            LabelValueBean data;
            for (Object obj : list) {
                CodeModel code = (CodeModel) obj;
                data = new LabelValueBean();
                data.setValue(code.getCodeId());
                data.setLabel(code.getCodeDesc());
                data.setAssigned(false);
                l.add(data);
            }
            return l;
        }
        return new ArrayList();
    }

    public List getSearchUserList() {
        //search 创建人
        List list = codeLookupMgr.getCodeListWithFilter(CodeConstant.USER_LIST, CodeConstant.CODE_FILTER, new ArrayList(), true);
        return list;
    }

    public List getSearchAllUserList() {
        //search 处理人
        List list = codeLookupMgr.getCodeListWithFilter(CodeConstant.HANDLER_IND_LIST, CodeConstant.CODE_FILTER, new ArrayList(), true);
        return list;
    }

    public List getSearchSysUpdateStatusList() {
        List list = codeLookupMgr.getCodeList(CodeConstant.CODE_SYSUPDATE_STATUS_LIST);
        return list;
    }


    public List getSearchStatusList() {
        List list = codeLookupMgr.getCodeList(CodeConstant.CODE_STATUS_LIST, true);
        return list;
    }

    public PaginationHelper getSearchList(PaginationHelper helper, com.beilang.hotline.telrecord.to.SearchTO searchTO) {
        helper = telrecordMgr.getTelrecordList(this.getLoginUser(), helper, searchTO);
        return helper;
    }

    public List searchRecordAttachList(Long entityId, String entityType) {
        return telattachMgr.searchRecordAttachList(entityId, entityType);
    }

    public void deleteAttachList(List deleteList) {
        for (int i = 0; i < deleteList.size(); i++) {
            Integer attachId = (Integer) deleteList.get(i);
            telattachMgr.deleteTelattach(new Long(attachId));
        }
    }

    public void deleteReplyList(List deleteList) {
        for (int i = 0; i < deleteList.size(); i++) {
            Integer replyId = (Integer) deleteList.get(i);
            telreplyMgr.deleteTelreply(new Long(replyId));
        }
    }

    public void closeRecordList(List deleteList) {
        for (int i = 0; i < deleteList.size(); i++) {
            Integer recordId = (Integer) deleteList.get(i);
            TelrecordModel telrecordModel = telrecordMgr.getTelrecord(new Long(recordId));
            telrecordModel.setRecordStatus(Constant.STATUS_COMPLETE);
            telrecordMgr.saveTelrecord(telrecordModel);
        }
    }

    public void deleteRecordList(List deleteList) {
        for (int i = 0; i < deleteList.size(); i++) {
            Integer recordId = (Integer) deleteList.get(i);
            deleteTelrecord(new Long(recordId));
        }
    }

    public List searchRecordReplyList(int recordId, boolean isKeyIndicator) {
        List list = telreplyMgr.searchTelreplyList(new Long(recordId), isKeyIndicator);
        return list;
    }

    public TelreplyModel createTelreplyModel(TelreplyModel telreplyModel) {
        telreplyModel.setReplyTime(DateUtil.getDate());

        UserModel user = this.getLoginUser();
        if (user != null) {
            telreplyModel.setCreateId(user.getUserId());
            telreplyModel.setUpdateId(user.getUserId());
            telreplyModel.setReplyFrom(user.getUserId());
        }
        Date date = DateUtil.getDate();
        telreplyModel.setCreateTime(date);
        telreplyModel.setUpdateTime(date);

        telreplyModel = telreplyMgr.createTelreplyModel(telreplyModel);
        sendEmail(telreplyModel);
        return telreplyModel;
    }

    public TelreplyModel getTelreplyModelById(int replyId) {
        return telreplyMgr.getTelreply(new Long(replyId));
    }

    public void saveTelreplyModel(TelreplyModel telreplyModel) {
        telreplyMgr.saveTelreplyModel(telreplyModel);
        sendEmail(telreplyModel);

    }

    public void sendEmail(TelreplyModel telreplyModel) {
        String nowOwner = telreplyModel.getReplyBy();
        TelrecordModel telrecordModel = telrecordMgr.getTelrecord(telreplyModel.getRecordId());
        String currentOwner = telrecordModel.getCurrentOwner();
        UserModel loginUser = this.getLoginUser();
        if (!StringUtil.isEmpty(currentOwner) && !StringUtil.isEmpty(nowOwner)) {
            if (!currentOwner.equals(nowOwner)) {
                EmailServerModel emailServerModel = emailServerMgr.getEmailServer();
                String from = emailServerModel.getEmailFrom();
                String displayName = emailServerModel.getEmailDisplayName();
                UserModel userModel1 = userMgr.getUser(currentOwner);
                UserModel userModel2 = userMgr.getUser(nowOwner);
                ArrayList tolist = new ArrayList();
                if (!StringUtil.isEmpty(userModel1.getEmailAddress()) && !loginUser.getUserId().equalsIgnoreCase(userModel1.getUserId())) {
                    tolist.add(userModel1.getEmailAddress());
                }
                if (!StringUtil.isEmpty(userModel2.getEmailAddress()) && !loginUser.getUserId().equalsIgnoreCase(userModel2.getUserId())) {
                    tolist.add(userModel2.getEmailAddress());
                }
                String mailhost = emailServerModel.getSmtpServer();
                String userName = emailServerModel.getEmailUserName();
                String password = emailServerModel.getEmailPassword();
                String mailSubject = emailServerModel.getEmailSubject();
                if (!tolist.isEmpty()) {
                    SendEmailUtil.sendMail(from, displayName, tolist, mailhost, userName, password, mailSubject, telreplyModel, telrecordModel, emailServerModel);
                }
                telrecordModel.setCurrentOwner(nowOwner);
                telrecordMgr.saveTelrecord(telrecordModel);
            }
        }
    }

    public List getSearchCompanyListEmpty() {
        List list = new ArrayList();
        list.add(getEmptyCodeModel());
        list.addAll(getAddCompanyList(""));
        return list;
    }

    public List getSearchCompanyList() {
        List list = new ArrayList();
        list.add(getEmptyCodeModel());
        list.addAll(getAddCompanyList(""));
        return list;
    }

    public List getSearchCompanyListByTelephone() {
        List list = new ArrayList();
        list.addAll(getAddCompanyList(""));
        return list;
    }

    public List getSearchCompanyListFilter(String companyName) {
        List list = new ArrayList();
        if (StringUtil.isEmpty(StringUtil.trim(companyName)))
        {
            list.add(getEmptyCodeModel());
        }
        list.addAll(getAddCompanyList(companyName));
        return list;
    }

    public List getAddCompanyList(String companyName) {
        List companyTypeList = new ArrayList();
        UserModel user = this.getLoginUser();
        if (user != null) {
            companyTypeList = user.getAccessCompanyList();
        }

        return telrecordMgr.getSearchCompanyList(companyName, companyTypeList);
    }

    public TelrecordModel getSysteId(Long id, String idType) {
        if ("record".equals(idType)) {
            TelrecordModel temp = telrecordMgr.getTelrecord(id);
            return temp;
        } else if ("reply".equals(idType)) {
            TelreplyModel temp = telreplyMgr.getTelreply(id);
            TelrecordModel temp1 = telrecordMgr.getTelrecord(temp.getRecordId());
           return temp1;
        }
        return null;
    }
    public TelrecordModel updateSysStatus(TelrecordModel telrecordModel) {
         TelrecordModel temp = telrecordMgr.getTelrecord(telrecordModel.getRecordId());
         temp.setSystemUpdateStatus(telrecordModel.getSystemUpdateStatus());
         telrecordMgr.saveTelrecord(temp);
         return temp;
    }

    public Long createTelrecord() {
        TelrecordModel telrecordModel = new TelrecordModel();
        telrecordModel.setRecordTime(DateUtil.getDate());
        telrecordModel.setCustomerViewInd(Constant.YES);
        telrecordModel.setAccessInd(Constant.YES);
        telrecordModel.setRecordStatus(Constant.STATUS_INPROGRESS);


        UserModel user = this.getLoginUser();
        if (user != null) {
            telrecordModel.setCreateId(user.getUserId());
            telrecordModel.setUpdateId(user.getUserId());
            telrecordModel.setCurrentOwner(user.getUserId());
        }
        Date date = DateUtil.getDate();
        telrecordModel.setCreateTime(date);
        telrecordModel.setUpdateTime(date);

        TelrecordModel result = telrecordMgr.createTelrecord(telrecordModel);
        return result.getRecordId();
    }

    public int computeWorkDay(String startDate, String endDate) {
        int i = DateUtil.getWorkingDateRange(DateUtil.parse(startDate), DateUtil.parse(endDate));
        return i;
    }


    public PersonModel getCompanyPersonByTelephone(String telephonenumber) {
        return telrecordMgr.getCompanyPersonByTelephone(telephonenumber);
    }
}
